package com.news.servlet;

import com.news.model.User;
import com.news.service.UserService;
import com.news.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");

            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            String agree = request.getParameter("agree");

            if (agree == null) {
                request.setAttribute("message", "必须同意服务条款才能注册");
                request.getRequestDispatcher("register.jsp").forward(request, response);
                return;
            }

            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);

            String message = userService.register(user);
            
            if (message == null) {
                // 注册成功，设置提示信息并重定向到登录页面
                HttpSession session = request.getSession();
                session.setAttribute("message", "注册成功！请登录");
                response.sendRedirect("login.jsp");
            } else {
                request.setAttribute("message", message);
                request.getRequestDispatcher("register.jsp").forward(request, response);
            }
        } catch (Exception e) {
            request.setAttribute("message", "注册失败：" + e.getMessage());
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
} 